﻿using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ZechatApp.Services;

public class HttpServerService
{
    public async Task<string> StartListenerAsync()
    {
        HttpListener listener = new();

        listener.Prefixes.Add($"http://localhost:{App.ListenPort}/msg/");

        try
        {
            listener.Start();
            Console.WriteLine($"Listening on port {App.ListenPort}...");

            while (true)
            {
                var context = await listener.GetContextAsync();
                var request = context.Request;
                var response = context.Response;

                string requestData = await new System.IO.StreamReader(request.InputStream).ReadToEndAsync();
                Console.WriteLine($"Received data: {requestData}");

                string responseString = "Data received successfully";
                byte[] buffer = Encoding.UTF8.GetBytes(responseString);
                response.ContentLength64 = buffer.Length;
                await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);

                response.Close();

                return $"Received: {requestData}";
            }
        }
        catch (Exception ex)
        {
            return $"Error in listener: {ex.Message}";
        }
    }
}